﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using MMITPinGen.Entities;
using System.IO;
using MMITDomain;
using MMITDomain.Concrete;

namespace MMITPinGen
{
    public partial class InjectPINsToDB : System.Web.UI.Page
    {
        EFBatchRepository BatchRepository = new EFBatchRepository();
        EFPartnerRepository PartnerRespository = new EFPartnerRepository();
        EFPINRepository PINRepository = new EFPINRepository();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                List<string> roles = Roles.GetRolesForUser(User.Identity.Name).ToList();
                var r = from p in roles
                        where p == "Partner"
                        select p;
                if (r.Count() == 0)
                {
                    lblMsg.Text = "You do not have permission to perform this function. Please contact Customer Service";
                    grdBatches.Visible = false;
                }

                int PartnerId = (from p in PartnerRespository.Partners
                                 where p.Name == User.Identity.Name
                                 select p.Id).FirstOrDefault();
                
                List<Batch> bat = (from p in BatchRepository.Batches
                                   where p.Status == 1 && p.PartnerId == PartnerId
                                   select p).ToList();
                if (bat.Count() > 0)
                {
                    grdBatches.DataSource = bat;
                    grdBatches.DataBind();
                }
                else
                {
                    lblMsg.Text = "No Batches Available for Download";
                }
               
                                                   
            }
        }

        protected void grdBatches_SelectedIndexChanged(object sender, EventArgs e)
        {
            var t = grdBatches.SelectedItems;
            HiddenField k = (HiddenField)t[0].FindControl("HiddenField1");

            string[,] HeaderAndColumns = new string[,] {
            {"PIN",      "PINNumber"},
            {"SerialNumber","SerialNo"},
            {"DateGenerated","DateGenerated"},
             {"Voucher Value","Value"}
            };



          

            Batch b =  BatchRepository.GetBatchById(Convert.ToInt32(k.Value));
            if (b.Status == 2)
            { 
                lblMsg.Text = "This Batch has Been Downloaded Already";
                HttpContext.Current.Response.End();
                
            }
            b.Status = 2;
            b.DateFetched = DateTime.Now;
            BatchRepository.SaveBatch(b);

            int PartnerId = (from p in PartnerRespository.Partners
                             where p.Name == User.Identity.Name
                             select p.Id).FirstOrDefault();

            List<Batch> bat = (from p in BatchRepository.Batches
                               where p.Status == 1 && p.PartnerId == PartnerId
                               select p).ToList();
            if (bat.Count() > 0)
            {
                grdBatches.DataSource = bat;
                grdBatches.DataBind();
            }
            else
            {
                lblMsg.Text = "No Batches Available for Download";
            }

            List<PIN> LP = (from p in PINRepository.PINs
                            where p.BatchId == b.Id
                            select p).ToList();

            
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.AddHeader(
                "content-disposition", string.Format("attachment; filename={0}", b.Name +"_" + DateTime.Now.ToString("") + ".csv"));
            HttpContext.Current.Response.ContentType = "application/ms-excel";

            using (StringWriter objSw = new StringWriter())
            {
                
                objSw.Write( ListToCsv(ref LP, HeaderAndColumns));
                HttpContext.Current.Response.Write(objSw.ToString());
                HttpContext.Current.Response.End();
            }

          

        }

        private static string ListToCsv(ref List<PIN> list, string[,] HeaderAndColumns)
        {
            if (list == null || list.Count == 0) return "";

            Type t = typeof(Batch);
            int lenght = HeaderAndColumns.GetLength(0);

            StringWriter sw = new StringWriter();

            // Create Header Row..
            for (int l = 0; l < lenght; l++)
            {
                sw.Write(HeaderAndColumns[l, 0].Replace(',', ' '));
                if (l < lenght - 1)
                    sw.Write(",");
            }
            sw.Write(sw.NewLine);

            //this acts as datarow

            foreach (PIN item in list)
            {
                for (int i = 0; i < lenght; i++)
                {
                    string whatToWrite =
                        Convert.ToString(item.GetType().GetProperty(HeaderAndColumns[i, 1]).GetValue(item, null)).Replace(',', ' ');

                    if (i < lenght - 1)
                        whatToWrite += ",";

                    sw.Write(whatToWrite);
                }
                sw.Write(sw.NewLine);
            }

            return sw.ToString();
        }

        protected void lnkNew_Click(object sender, EventArgs e)
        {

        }
    }
}